package com.da.auth.security.config;

import com.alibaba.fastjson.JSON;
import com.da.common.utils.DailyAimResult;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * @Author: hyacinth
 * @CreateTime: 2025-02-10
 * @Version: 1.0
 */
@Component
@Slf4j
public class UserAccessDeniedHandler implements AccessDeniedHandler {

    /**
     * 处理访问被拒绝的情况，返回自定义的错误信息
     *
     * @param request               当前的HTTP请求
     * @param response              当前的HTTP响应
     * @param accessDeniedException 访问拒绝异常对象
     * @throws IOException      如果在处理请求或响应时发生I/O错误
     * @throws ServletException 如果在处理请求或响应时发生Servlet错误
     */
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        log.error("权限不足，URI：{}，异常：{}", request.getRequestURI(), accessDeniedException.getMessage());
        // 发生这个行为，做响应处理，给一个响应的结果
        response.setContentType("application/json;charset=utf-8");
        // 构建输出流对象
        ServletOutputStream outputStream = response.getOutputStream();
        // 调用fastjson工具，进行Result对象序列化
        String error = JSON.toJSONString(DailyAimResult.error("权限不足，请联系管理员"));
        outputStream.write(error.getBytes(StandardCharsets.UTF_8));
        outputStream.flush();
        outputStream.close();
    }
}
